package cn.com.gridinfo.sooc.core.login.activity.forgetpwd;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.telephony.TelephonyManager;

import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.jeremy.arad.utils.AnimUtil;
import com.jeremy.arad.utils.Log;
import com.jeremy.arad.utils.StringUtils;

import java.util.Vector;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.base.BaseSoocActivity;
import cn.com.gridinfo.sooc.core.login.common.CodeConst;
import cn.com.gridinfo.sooc.core.login.dao.ForgetDao;
import cn.com.gridinfo.sooc.core.my.setting.activity.MiBaoActivity;
import cn.com.gridinfo.sooc.utils.MessageUtils;
import cn.com.gridinfo.sooc.utils.widget.ClearEditText;

/**
 * 通过手机号找回
 * By 刘晓晨
 */
public class BackPwdTelActivity extends BaseSoocActivity {

    @InjectView(R.id.yourPhoneNumber)
    TextView yourPhoneNumber;//显示用户电话号码
    @InjectView(R.id.getCode)
    Button getCode;//获得验证码
    @InjectView(R.id.submit)
    Button submit;//提交
    @InjectView(R.id.yanzhengma)
    ClearEditText yanzhengma;//验证码输入框
    private String myPhoneNumber;//电话号码（带****用来显示）
    private String realNumber;//电话号码（不带****，用来获取验证码）
    private String imei;//硬件标识码
    private String xtdz;//节点域名
    private int yanzhengcode = 1;//验证码 预设
    private String uid;//用户id
    private String type = "tel"; //找回方式
    private ForgetDao dao;//用户dao
    private String way;//从那个地方调用的这个程序 000：从设置中 111：从忘记密码中
    private String rNumber;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.back_pwd_tel_activity);
        ButterKnife.inject(this);
        dao = new ForgetDao(this);
        way = getIntent().getStringExtra("way");//从哪个地方调用的这个程序 000：从设置中 111：从忘记密码中
        myPhoneNumber = getIntent().getStringExtra("phoneNumber");//拿到上个页面传来的电话号码 ****
        realNumber = getIntent().getStringExtra("realNumber");//拿到上个页面传来的电话号码(忘记密码）
        rNumber = getIntent().getStringExtra("pNumber");//拿到上个页面传来的电话号码（密保 验证）
        xtdz = getIntent().getStringExtra("xtdz");//拿到节点
        uid = getIntent().getStringExtra("uid");//拿到用户id
        dao.setXtdz(xtdz);
        Log.d("忘记密码点进来的手机号：" + realNumber);

        try {//拿 imei码
            TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
            imei = telephonyManager.getDeviceId();
        } catch (SecurityException e) {
            e.printStackTrace();
        } finally {
            if (imei == null || "".equals(imei)) {
                imei = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
            }
        }
        Log.d("密保手机验证点进来的手机号:" + myPhoneNumber);
        Log.d("imei" + imei);
        yourPhoneNumber.setText(myPhoneNumber);//显示手机号（隐藏4位）
        submit.setEnabled(false);
        yanzhengma.setImeOptions(EditorInfo.IME_ACTION_NEXT);
        yanzhengma.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_NEXT) {
                    if (validateNotNull()) {
                        tijiao();
                    }

                }
                return false;
            }
        });

    }

    private boolean validateNotNull() {//账号为空
        if(StringUtils.isNull(yanzhengma.getText().toString().trim())){
            yanzhengma.requestFocus();
            return false;
        }
        return true;
    }

    //设置标题
    @Override
    public String setupToolBarTitle() {
        return "手机号码找回";
    }

    @Override
    public boolean setupToolBarLeftButton(ImageView leftButton) {
        return true;
    }

    //ToolBar的back键
    @OnClick(R.id.toolbar_leftbtn)
    void onToolbarLeftClick() {
        finish();
    }

    //倒计时
    private CountDownTimer timer = new CountDownTimer(59000, 1000) {
        //  倒计时过程，不能点击
        @Override
        public void onTick(long millisUntilFinished) {
            getCode.setEnabled(false);
            getCode.setClickable(false);
            getCode.setText("已发送" + (millisUntilFinished / 1000) + "秒");
        }

        //倒计时完成 可以点击
        @Override
        public void onFinish() {
            getCode.setEnabled(true);
            getCode.setClickable(true);
            getCode.setText("重新发送");
            getCode.setTextColor(getResources().getColor(R.color.white));
        }
    };

    @Override
    public void onRequestSuccess(int requestCode) {
        super.onRequestSuccess(requestCode);
        if (dao.status.equals("0")) {
            switch (requestCode) {
                case CodeConst.GET_FORGETYZM:

                    MessageUtils.showRightImageShortToast(this, dao.getStatusCode());
                    break;
                case CodeConst.YZM_SURE://验证手机号通过
//                if (dao.status.equals("0")) {
                    if (way.equals("111")) {//从哪里点击进入的该activity 111：忘记密码
                        Intent i = new Intent(this, ResetPwdActivity.class);
                        i.putExtra("xtdz", xtdz);//将节点域名传递
                        i.putExtra("uid", uid);//将用户uid传递
                        i.putExtra("type", type);//将找回方式传递
                        startActivity(i);
                        finish();
                        AnimUtil.intentSlidIn(this);
                    } else if (way.equals("000")) {//从哪里点击进入的该activity  000：修改密保问题
                        startActivity(new Intent(this, MiBaoActivity.class));
                        setResult(RESULT_OK);
                        finish();
                        AnimUtil.intentSlidIn(this);
                    }
            }
        } else {
            MessageUtils.showImageShortToast(this, dao.statusCode);
        }
    }

    //请求失败
    @Override
    public void onRequestFaild(int requestCode, String errorNo, String errorMessage) {
        super.onRequestFaild(requestCode, errorNo, errorMessage);
        MessageUtils.showShortToast(this, dao.getStatusCode());
    }

    //点击获取验证码
    @OnClick(R.id.getCode)
    void setGetCode() {
        if (way.equals("000")) {//是从密保问题进来的，
            realNumber = rNumber;//请求数据需要，
        }
        Log.d("我的手机号！" + realNumber);
        Log.d("登录系统版本！" + Build.VERSION.RELEASE);
        Log.d("登录设备型号！" + Build.MODEL);
        Log.d("imei码！" + imei);
        dao.getYanzhengma(realNumber, 1,
                Build.VERSION.RELEASE, Build.MODEL, imei);
        timer.start();//发送验证码倒计时
        getCode.setEnabled(false);
        getCode.setClickable(false);
        getCode.setTextColor(getResources().getColor(R.color.color_b7));
    }

    //点击 下一步
    //验证验证码是否正确
    @OnClick(R.id.submit)
    void tijiao() {
        yanzhengcode = Integer.parseInt(yanzhengma.getText().toString());
        dao.suerYanzhengma(realNumber, yanzhengcode, realNumber + yanzhengcode +
                "0S3FV7PH8MLJT6IOAG2ECWQNXUBR1YZ459KD");

    }

    //监听输入框状态，都有信息才可以点击按钮
    @OnTextChanged(value = R.id.yanzhengma, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void onAfterTextChanged() {
        if (StringUtils.isNull(yanzhengma.getText().toString())) {
            submit.setEnabled(false);
        } else {
            submit.setEnabled(true);
        }
    }

}
